package tools

import (
	"errors"
	"fmt"
	"hft/e"
	"hft/global"
	"time"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi "github.com/alibabacloud-go/dysmsapi-20170525/v3/client"
	"github.com/alibabacloud-go/tea/tea"
)

type AliyunSms struct{}

func NewSms() (result *dysmsapi.Client, err error) {
	config := &openapi.Config{
		AccessKeyId:     &global.OC_CONFIG.AliyunSms.AccessKeyId,
		AccessKeySecret: &global.OC_CONFIG.AliyunSms.AccessKeySecret,
	}
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")

	client, err := dysmsapi.NewClient(config)

	return client, err
}

// 发送验证码
func (*AliyunSms) SendValid(prefix string, phone string, model string) {
	// s, _ := NewSms()

	// request := &dysmsapi.SendSmsRequest{}

	// request.SetPhoneNumbers(phone)

	// request.SetSignName(global.OC_CONFIG.AliyunSms.SignName)

	// request.SetTemplateCode(model)

	code := RandValid()

	fmt.Println(code, "验证码")

	// request.SetTemplateParam(fmt.Sprintf("{code:%v}", code))

	// res, err := s.SendSms(request)

	// if err != nil {
	// 	fmt.Println(err, res)
	// }

	// fmt.Println(res, err, phone)

	//设置过期时间

	global.OC_REDIS.Set(prefix+phone, code, 5*time.Minute)

}

func (*AliyunSms) VerifyValid(prefix string, phone string, code string) (err error) {

	key, err := global.OC_REDIS.Get(prefix + phone).Result()

	if err != nil {
		return errors.New(e.CodeExpire)
	}
	fmt.Println(key, code)
	if key == code {
		global.OC_REDIS.Del(prefix + phone)
		return nil
	} else {
		return errors.New(e.CodeInValid)
	}
}

var AliyunSmsTool = new(AliyunSms)
